import axios, { type AxiosRequestConfig, type AxiosError } from 'axios';
import { authService } from '@/service/AuthService';

export function initAxios() {
    axios.defaults.baseURL = import.meta.env.VITE_API_URL;

    let refreshTokenPromise: Promise<any> | null = null;

    function retryAfterRefreshToken(originalConfig: AxiosRequestConfig) {
        if (!refreshTokenPromise) {
            refreshTokenPromise = authService.refreshToken()
                .catch((error) => {
                    return Promise.reject(error);
                })
                .finally(() => {
                    refreshTokenPromise = null;
                });
        }

        return refreshTokenPromise.then(() => {
            const accessToken = sessionStorage.getItem("access_token");
            if (accessToken) {
                originalConfig.headers = originalConfig.headers || {}; // 确保 headers 存在
                originalConfig.headers.Authorization = `Bearer ${accessToken}`;
            }
            return axios(originalConfig);
        });
    }

    // 请求拦截器
    axios.interceptors.request.use(
        (config) => {
            const accessToken = sessionStorage.getItem("access_token");
            if (accessToken) {
                config.headers = config.headers || {}; // 确保 headers 存在
                config.headers.Authorization = `Bearer ${accessToken}`;
            }
            return config;
        },
        (error) => Promise.reject(error)
    );

    // 响应拦截器
    axios.interceptors.response.use(
        (response) => response,
        (error: AxiosError) => {
            const originalRequest = error.config as AxiosRequestConfig & { _retry?: boolean };

            if (error.response?.status === 401 && !originalRequest._retry) {
                originalRequest._retry = true;
                return retryAfterRefreshToken(originalRequest);
            }

            return Promise.reject(error);
        }
    );
}